package com.xunlai.infra.permission.manager.web.controller;

import com.xunlai.infra.permission.common.exception.PermissionBusinessException;
import com.xunlai.infra.permission.manager.web.service.DepartmentService;
import com.xunlai.infra.permission.manager.web.vo.BaseResponse;
import com.xunlai.infra.permission.manager.web.vo.department.CreateDepartmentReqVo;
import com.xunlai.infra.permission.manager.web.vo.department.DepartmentListVo;
import com.xunlai.infra.permission.manager.web.vo.department.QueryDepartmentVo;
import com.xunlai.infra.permission.manager.web.vo.department.UpdateDepartmentReqVo;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author liang
 * @date 12/11/22 9:16 PM
 */
@PreAuthorize("hasAnyRole('ADMIN','SUPER_ADMIN')")
@RestController
@RequestMapping("system/department")
public class DepartmentController {

    private DepartmentService departmentService;


    @PostMapping("create")
    public BaseResponse<Long> create(@RequestBody @Validated({CreateDepartmentReqVo.ValidCreateDepartmentGroup.class}) CreateDepartmentReqVo createDepartmentReqVo) {
        return BaseResponse.success(departmentService.createDepartment(createDepartmentReqVo), "SUCCESS");
    }

    @PostMapping("batchCreate")
    public BaseResponse<List<Long>> create(@RequestBody @Validated({CreateDepartmentReqVo.ValidCreateDepartmentGroup.class}) List<CreateDepartmentReqVo> createDepartmentReqVo) {
        return BaseResponse.success(departmentService.createDepartment(createDepartmentReqVo), "SUCCESS");
    }

    @GetMapping("list")
    public BaseResponse<List<DepartmentListVo>> list(QueryDepartmentVo queryDepartmentVo) {
        return BaseResponse.success(departmentService.listDepartment(queryDepartmentVo), "SUCCESS");
    }

    @PutMapping("update")
    public BaseResponse<Void> update(@RequestBody @Validated({UpdateDepartmentReqVo.ValidUpdateDepartmentGroup.class}) UpdateDepartmentReqVo updateDepartmentReqVo) {
        try {
            departmentService.updateDepartment(updateDepartmentReqVo);
            return BaseResponse.success(null, "SUCCESS");
        } catch (PermissionBusinessException e) {
            return BaseResponse.error(e.getCode(), null, e.getMsg());
        }
    }

    @DeleteMapping("/{id}")
    public BaseResponse<Boolean> update(@PathVariable Long id,@RequestParam(required = false,defaultValue = "0") Integer recursive ) {
        return BaseResponse.success(departmentService.deleteDepartment(id,recursive == 1), "SUCCESS");
    }

    @Autowired
    public void setDepartmentService(DepartmentService departmentService) {
        this.departmentService = departmentService;
    }
}
